package com.newhero.app.report.site.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newhero.app.report.persistence.entity.Disclose;
import com.newhero.app.report.persistence.entity.Post;
import com.newhero.app.report.persistence.entity.ProblemQuality;
import com.newhero.app.report.persistence.entity.ReportKind;
import com.newhero.app.report.persistence.entity.ReportRegion;
import com.newhero.app.report.site.service.ISiteService;
import com.newhero.app.report.utils.DESFileUtil;
import com.newhero.app.report.utils.StringSubStr;
import com.newhero.product.common.controller.BaseController;
import com.newhero.product.common.mybatis.toolkit.IdWorker;
import com.newhero.product.common.util.CaptchaUtils;
import com.newhero.product.common.util.GTime;
import com.newhero.product.common.util.StringUtils;
import com.newhero.product.common.vo.Json;
import com.newhero.product.common.vo.ZTreeModel;

 /**
 * @ClassName: SiteController
 * @Description: 界面访问控制类
 * @author zlf
 * @date 2018-09-07
 */
@Controller
@RequestMapping("/web")
public class SiteController extends BaseController {
    @Autowired 
    private ISiteService siteServiceImpl;
    
    
    /**
	 * 首页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/index.html", method = RequestMethod.GET)
	public String index() {

		return "site/index";
	}
	
	/**
	 * 举报页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/report.html", method = RequestMethod.GET)
	public String report(String kindId,String discloseType,HttpServletRequest request) {

		request.setAttribute("kindId", kindId);
		request.setAttribute("discloseType", discloseType);
		
		return "site/report";
	}
	
	 /**
	 * 须知
	 * 
	 * @return
	 */
	@RequestMapping(value = "/xuzhi.html", method = RequestMethod.GET)
	public String xuzhi(String regionCode,String kindId, HttpServletRequest request) {

		request.setAttribute("regionCode", regionCode);
		request.setAttribute("kindId", kindId);
		return "site/xuzhi";
	}
	/**
	 * fankui
	 * 
	 * @return
	 */
	@RequestMapping(value = "/fankui.html", method = RequestMethod.GET)
	public String fankui() {

		return "site/fankui";
	}
	/**
	 * returnFankui
	 * 
	 * @return
	 */
	@RequestMapping(value = "/fankuiQuery.html", method = RequestMethod.POST)
	@ResponseBody
	public Object returnFankui(String regionCode,String captcha,HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		String sessionCaptcha = session.getAttribute("CAPTCHA").toString();
		Map<String,Object> map = new HashMap<String,Object>();
		if(sessionCaptcha.equals(captcha.toUpperCase())){
			Disclose disclose= null;
			if(null != regionCode && !regionCode.equals("")){
				try{
					String reportCode = DESFileUtil.encryptStr(regionCode);
					disclose = siteServiceImpl.getDiscloseByReportCode(reportCode);
				}catch(Exception e){
					map.put("flag", "0");
					map.put("msg", "系统错误请联系管理员!");
					return renderSuccess(map);
				}
			}
			
			if(disclose == null){
				map.put("flag", "0");
				map.put("msg", "查询码输入错误，请重新输入!");
			}else{
				map.put("flag", "1");
			}
			return renderSuccess(map);
		}else{
			map.put("flag", "0");
			map.put("msg", "验证码输入错误!");
			return renderSuccess(map);
		}
	}
	
	/**
	 * 查询成果返回界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/returnfankui.html", method = RequestMethod.GET)
	public String returnfankui() {

		return "site/returnfankui";
	}
	
	 /**
     * 举报人表单主页面
     * @return
     */
	@RequestMapping(value = "/peopleMain.html", method = RequestMethod.GET)
	public String peopleMain(String kindId,String regionCode, HttpServletRequest request) {
	
		request.setAttribute("regionCode", regionCode);
		request.setAttribute("kindId", kindId);
		return "/site/peopleMain";
	}
	
	 /**
     * 举报单位表单主页面
     * @return
     */
	@RequestMapping(value = "/unitMain.html", method = RequestMethod.GET)
	public String unitMain(String kindId,String regionCode, HttpServletRequest request) {
	
		request.setAttribute("regionCode", regionCode);
		request.setAttribute("kindId", kindId);
		return "/site/unitMain";
	}
    /**
     * 举报单位表单页面
     * @return
     */
	@RequestMapping(value = "/reportUnit.html", method = RequestMethod.GET)
	public String discloseForm(String discloseId,String kindId,String regionCode,HttpServletRequest request) {
		
		//信息种类
		List<ReportKind> reportKindList = siteServiceImpl.findReportKindList();
		request.setAttribute("reportKindList", reportKindList);
		
		//级别
		String 	postKind = "unit";	
		List<Post> postList = siteServiceImpl.findPostList(postKind);
		request.setAttribute("postList", postList);
	
	    Map<String, Object> map = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(regionCode)){
			ReportRegion reportRegion = siteServiceImpl.getReportRegionById(regionCode);
			map.put("mxcode", reportRegion.getRegionCode());
			map.put("mxname", reportRegion.getRegionName());
		}
		request.setAttribute("discloseId", "");
		map.put("discloseType", "1");
		request.setAttribute("kindId", kindId);
		request.setAttribute("formData", map);
		
		return "/site/reportUnit";
	}
	
	@RequestMapping(value = "/findAllProblemQualityList", method ={RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public List<ZTreeModel> findAllProblemQualityList(@RequestParam(value = "pid", defaultValue = "", required = false)
		String pid,
		HttpServletRequest request){
		String[] str = pid.split(",");
		//问题性质
		List<ProblemQuality> problemQualityList = siteServiceImpl.problemQualityList();
				
		List<ZTreeModel> treeList = new ArrayList<ZTreeModel>();
		
		for (int i = 0; i < problemQualityList.size(); i++) {
			ProblemQuality problemQuality = problemQualityList.get(i);
			String problemName = problemQuality.getProblemName();
			ZTreeModel atm = new ZTreeModel(problemQuality.getPid(), "",problemName, true, "");
			for (int j = 0; j < str.length; j++){
				if(str[j].equals(problemQuality.getPid())){
					atm.setChecked(true);
				}
			}
				treeList.add(atm);
				
		}
		return treeList;
	}
	
	@RequestMapping(value = "/findProblemList", method ={RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public  Object findProblemList(@RequestParam(value = "pid", defaultValue = "", required = false)
		String pid,
		HttpServletRequest request){
		
		Map<String,String> map = new HashMap<String,String>();
		//问题性质
		List<ProblemQuality> problemQualityList = siteServiceImpl.problemQualityList();
		for(ProblemQuality problemQuality :problemQualityList){
			map.put(problemQuality.getProblemNo(), problemQuality.getProblemName());
		}
		
		return renderSuccess(map);
	}
		
				
	/**
     * 举报人表单页面
     * @return
     */
	@RequestMapping(value = "/reportPeople.html", method = RequestMethod.GET)
	public String discloseUnitForm(String discloseId,String kindId,String regionCode, HttpServletRequest request) {
		
		
		//信息种类
		List<ReportKind> reportKindList = siteServiceImpl.findReportKindList();
		request.setAttribute("reportKindList", reportKindList);
		
		//级别
		String 	postKind = "people";	
		List<Post> postList = siteServiceImpl.findPostList(postKind);
		request.setAttribute("postList", postList);
		
		//问题性质
		//List<ProblemQuality> problemQualityList = siteServiceImpl.problemQualityList();
		
		//request.setAttribute("problemList", problemQualityList);
		
		    Map<String, Object> map = new HashMap<String, Object>();
			if(StringUtils.isNotBlank(regionCode)){
				ReportRegion reportRegion = siteServiceImpl.getReportRegionById(regionCode);
				if(reportRegion != null){
					map.put("mxcode", reportRegion.getRegionCode());
					map.put("mxname", reportRegion.getRegionName());
				}else{
					
					return null;
				}
				
			}
			request.setAttribute("discloseId", "");
			map.put("discloseType", "0");
			request.setAttribute("kindId", kindId);
			request.setAttribute("formData", map);
			
		return "/site/reportPeople";
	}
	
    /**
     * 表单保存
     * @throws Exception 
     */
	@RequestMapping(value = "/Save.html", method = RequestMethod.POST)
	//public String discloseSave(
	@ResponseBody
	public Object discloseSave(String discloseId, Disclose disclose, String captcha,
			HttpServletRequest request,HttpServletResponse response, ModelMap model) throws Exception {
		
		HttpSession session = request.getSession();
		String sessionCaptcha = session.getAttribute("CAPTCHA").toString();
		
		
		String postId = "";
		//级别名称
		String postName = "";
		if((disclose.getDiscloseType() != null) && (0 == disclose.getDiscloseType())){
			postId = disclose.getReportedLevel();
		}else{
			postId = disclose.getReportedUnitLevel();
		}
		Post post = siteServiceImpl.getPostById(postId);
		if(post != null){
			postName = post.getPostName();	
		}
		

		String kindName = "";
		if(!"".equals(disclose.getKindId())){
			kindName = siteServiceImpl.getReportKindById(disclose.getKindId()).getKindName();
		}
		
		disclose.setKindName(kindName);
		disclose.setLevelName(postName);
		 //举报人Ip
    	String ip = StringSubStr.getRealIp();
    	
		if(sessionCaptcha.equals(captcha.toUpperCase())){
			
			int count = siteServiceImpl.getDisIpCount(ip);
			if(count >=5 ){
				return renderSuccess("举报人每天最多只能提交5件举报!");
			}
			//举报人姓名
			String reportName = StringSubStr.getContent(disclose.getReportedName(), 50, 1);
			
			String  reportCode = StringSubStr.getContent(disclose.getReportCode(),20,1);
			//举报人所在地区
			String  disRegion = StringSubStr.getContent(disclose.getDisRegion(),80,1);
			//举报人姓名
			String  disName = StringSubStr.getContent(disclose.getDisName(),50,1);
			//举报人单位
			String  disUnit = StringSubStr.getContent(disclose.getDisUnit(),30,1);
			//举报人职务
			String  disPost = StringSubStr.getContent(disclose.getDisPost(),30,1);
			//举报人身份证号
			String  identityCard = StringSubStr.getContent(disclose.getIdentityCard(),40,1);
			//举报人邮编
			String  zipCode = StringSubStr.getContent(disclose.getZipCode(),20,1);
			//举报人地址
			String  address = StringSubStr.getContent(disclose.getAddress(),100,1);
			//举报人电话
			String  phone = StringSubStr.getContent(disclose.getPhone(),30,1);
			//举报人手机
			String  telephone = StringSubStr.getContent(disclose.getTelephone(),30,1);
			//举报人邮箱
			String  email = StringSubStr.getContent(disclose.getEmail(),30,1);
			//被举报人名称
			String  reportedName = StringSubStr.getContent(disclose.getReportedName(),50,1);
			//被举报人政治面貌
			String  reportedZzmm = StringSubStr.getContent(disclose.getReportedZzmm(),30,1);
			//被举报人所在单位
			String  reportedUnit = StringSubStr.getContent(disclose.getReportedUnit(),100,1);
			//被举报人职务
			String  reportedPost = StringSubStr.getContent(disclose.getReportedPost(),20,1);
			//被举报人地区
			String  reportedRegion = StringSubStr.getContent(disclose.getReportedRegion(),150,1);
              
			disclose.setKindName(kindName);
			disclose.setReportCode(reportCode);
			disclose.setDisRegion(disRegion);        
			disclose.setDisName(disName);          
			disclose.setDisUnit(disUnit);
			disclose.setDisPost(disPost);              
			disclose.setIdentityCard(identityCard);    
			disclose.setZipCode(zipCode);              
			disclose.setAddress(address);              
			disclose.setPhone(phone);                  
			disclose.setTelephone(telephone);          
			disclose.setEmail(email);                  
			disclose.setReportedName(reportedName);    
			disclose.setReportedZzmm(reportedZzmm);    
			disclose.setReportedUnit(reportedUnit);    
			disclose.setReportedPost(reportedPost);    
			disclose.setReportedRegion(reportedRegion);


			//内容长度截取
			String conStr = disclose.getMainContent();
			if(conStr.length() > 2500){
				conStr = conStr.substring(0, 2500);
			}
			if(conStr!=null){
				int sublen =3800;
				disclose.setMainContent(StringSubStr.getContent(conStr, sublen, 1));
				disclose.setMainContent1(StringSubStr.getContent(conStr, sublen, 2));
				
				String str1 = StringSubStr.getContent(conStr, sublen, 2);
				String str2 = "";
				if(str1.length() > 0 ){
					disclose.setMainContent2(StringSubStr.getContent(str1, 1900, 1));
					str2 = StringSubStr.getContent(str1, 1900, 1);
				}
				if(str2.length() > 0){
					
					disclose.setMainContent3(StringSubStr.getContent(str1, 900, 1));
				}
			}
			try {
				model.addAttribute("flag", "数据添加成功！");
				//举报事件时间
				//String ctime = GTime.getNormalTime();
				String ctime = GTime.getTime(GTime.YYYY_MM_DD);
				//当前年
				Calendar date = Calendar.getInstance();
		        String year = String.valueOf(date.get(Calendar.YEAR));
		        disclose.setYear(year);
				//自动生成ID查询码
		        String guid = IdWorker.get32UUID();
		        disclose.setReportCode(guid);
		        //ctime = DESFileUtil.encryptStr(ctime);
		        disclose.setDisDate(ctime);
		        disclose.setDateOrder(GTime.getTime(GTime.YYMMDDhhmmssxxx));
		    	disclose.setDisIp(ip);
		        disclose.setState(0);//是否受理 0:未受理 1:已受理
		        
				siteServiceImpl.saveDisclose(disclose);
				return renderSuccess("您的查询码是:"+guid);
			} catch (Exception e) {
				
				e.printStackTrace();
				logger.error(e);
			}
			
		}else{
			return renderSuccess("验证码输入错误!");
			/*if("1".equals(disclose.getDiscloseType())){
				//return "redirect:unitPeople";
				renderSuccess("登录成功");
			}else{
				//return "/site/reportPeople";
			}*/
		}
	 return 	renderSuccess("提交表单成功");
		//return "redirect:index";
	}
	
	@GetMapping("/captcha.jpg")
	public void captcha(HttpServletRequest request, HttpServletResponse response) {
		CaptchaUtils.generate(request, response);
	}
	
}
